package com.zzyl.nursing.service.impl;

import java.sql.Date;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.openai.core.JsonObject;
import com.zzyl.common.constant.DevicesAndProduct;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.GlobalException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.ExceptionUtil;
import com.zzyl.common.utils.HuaweiUtil;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.FunctionVo;
import com.zzyl.nursing.vo.ProductServicesVo;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 设备Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-20
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Resource
    private HuaweiUtil huaweiUtil;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    public static String secret;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 同步产品列表
     * @return
     */
    @Override
    public List<Device> syncProductList() {
        List<ProductSummary> productSummaries = huaweiUtil.get();
        redisTemplate.opsForValue().set(DevicesAndProduct.DEVICE_TYPE_PRODUCT, JSONUtil.toJsonStr(productSummaries), 60 * 60 * 24 + (int)(Math.random() * 100), TimeUnit.SECONDS);
        return null;
    }

    /**
     * 注册设备
     * @return
     */
    @Override
    public void register(DeviceDto deviceDto) {
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getSecret,secret);
        Device device1 = getOne(queryWrapper);
        if (device1 == null) {
        }else  {
            deviceMapper.deleteDeviceByIotId(device1.getIotId());
            huaweiUtil.DeleteDeviceSolution(device1.getIotId());
            this.secret = null;
        }
        addDevice(deviceDto,deviceDto.getNodeId());
    }

    /**
     * 设备详情查询
     * @param iotId
     * @return
     */
    @Override
    public DeviceVo queryDeviceDetail(String iotId) {
        DeviceVo deviceVo = new DeviceVo();
        DeviceDto deviceDto = new DeviceDto();
        deviceDto.setIotId(iotId);
        Device device1 = deviceMapper.selectByIotIdAndProductKey(deviceDto);
        if (device1 != null){
            deviceVo.setLocationType(device1.getLocationType());
            deviceVo.setBindingLocation(device1.getBindingLocation());
            deviceVo.setCreateTime(device1.getCreateTime());
            deviceVo.setRemark(device1.getRemark());
        }
        ShowDeviceResponse device = huaweiUtil.getDevice(iotId, device1.getProductKey());
        if(device != null){
        BeanUtils.copyProperties(device,deviceVo);
        deviceVo.setDeviceStatus(device.getStatus());
        deviceVo.setSecret(device.getAuthInfo().getSecret());
        deviceVo.setProductKey(device.getProductId());
        deviceVo.setIotId(device.getDeviceId());
        }
        this.secret = deviceVo.getSecret();
        return deviceVo;
    }

    /**
     * 删除设备
     * @param iotId
     */
    @Override
    public void deleteDeviceByIotId(String iotId) {
        deviceMapper.deleteDeviceByIotId(iotId);
        huaweiUtil.DeleteDeviceSolution(iotId);
        deviceDataMapper.deleteDeviceDataByiotId(iotId);
    }

    /**
     * 查询设备服务属性
     * @param iotId
     */
    @Override
    public List<DeviceDataVo> queryServiceProperties(String iotId) {
        List<DeviceDataVo> deviceDatas =new ArrayList<>();
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getIotId,iotId);
        Device device = deviceMapper.selectOne(queryWrapper);
        ShowDeviceShadowResponse showDeviceShadowResponse = huaweiUtil.queryServiceProperties(iotId, device.getProductKey());
        if (showDeviceShadowResponse.getHttpStatusCode()==200 && showDeviceShadowResponse.getShadow().size()!=0) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime dateTime = LocalDateTime.parse(showDeviceShadowResponse.getShadow().get(0).getReported().getEventTime(), formatter);
            Map properties = (Map)showDeviceShadowResponse.getShadow().get(0).getReported().getProperties();
            for(int i=0;i<properties.size();i++){
                DeviceDataVo deviceDataVo = new DeviceDataVo();
                String key = properties.keySet().toArray()[i].toString();
                String value = properties.get(key).toString();
                deviceDataVo.setValue(value);
                deviceDataVo.setFunctionId(key);
                deviceDataVo.setEventTime(dateTime);
                deviceDatas.add(deviceDataVo);
            }
        }
        return deviceDatas;
    }

    /**
     * 查询产品服务信息
     * @param productKey
     * @return
     */
    @Override
    public List<ProductServicesVo> queryProduct(String productKey) {
        List<ProductServicesVo> productServicesVos = new ArrayList<>();
        ShowProductResponse showProductResponse = huaweiUtil.queryProductInfo(productKey);
        if (showProductResponse.getHttpStatusCode()==200){
            showProductResponse.getServiceCapabilities().forEach(serviceCapability -> {
                ProductServicesVo productServicesVo = new ProductServicesVo();
                List<FunctionVo> properties = new ArrayList<>();
                productServicesVo.setService_id(serviceCapability.getServiceId());
                serviceCapability.getProperties().forEach(property -> {
                    String name = property.getPropertyName();
                    properties.add(new FunctionVo(name, name));
                });
                productServicesVo.setProperties(properties);
                productServicesVos.add(productServicesVo);
            });
            return productServicesVos;
        }
        return productServicesVos;
    }

    public void addDevice(DeviceDto deviceDto,String nodeId) {
        Device device = new Device();
        BeanUtils.copyProperties(deviceDto, device);
        if (nodeId == null || nodeId.length()==0){
        nodeId = UUID.randomUUID().toString();
        }
        device.setNodeId(nodeId);
        insertDevice(device);
        AddDeviceResponse res = huaweiUtil.add(deviceDto.getProductKey(), nodeId, deviceDto.getDeviceName(), deviceDto.getDeviceDescription());
        if (res != null) {
            device.setSecret(res.getAuthInfo().getSecret());
            device.setIotId(res.getDeviceId());
            device.setProductName(res.getProductName());
            updateDevice(device);
        } else {
            throw new GlobalException("失败");
        }
    }
}
